﻿/* $RCSFile: LeadProspector.ascx.cs $
 * Copyright (C) Addon Nice Technologies 2010
 * $Source: ?/Addon Nice/AddonNice/AddonNice.LeadProspection/PageModules/LeadProspector/LeadProspector.ascx.cs $
 * $log$
 * Revision 24 2010/08/09 11:16:26  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 11 2010/08/09 10:18:24  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
using System.Web.Configuration;
using AddonNice.Configuration.Settings;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.Generic;
using System.Web.Security;
using System.Xml;
using System.Configuration;

using AddonNice;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Core;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;

using AddonNice.LeadProspection.Settings;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.LeadProspector
{

    #region Local TraceSwitch 
	
    public class LeadProspectorTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("LeadProspectorTrace","Special Trace Switch for LeadProspector");
	}
	#endregion Local TraceSwitch 

    /// <summary>
    /// Initializer class for LeadProspector 
    /// </summary>
    public class LeadProspectorSI : PortalCRMModuleControlSI
    {
        public LeadProspectorSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose || LeadProspectorTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]LeadProspectorSI Ctor BEG.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:LeadProspectorTrace.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose || LeadProspectorTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]LeadProspectorSI Ctor END.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:LeadProspectorTrace.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose || LeadProspectorTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]LeadProspectorSI InitSettings BEG.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:LeadProspectorTrace.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                           =   pm.ExtendedResourcesGroup;

            SettingItemSpecial FixedProfile         =   new SettingItemSpecial(PStr.FixedProfile,new BooleanDataType());
            FixedProfile.Required                   =   false;
            FixedProfile.ResourceFile               =   PStr.ResourceFile;
            FixedProfile.ResourceItem               =   PStr.ResourceItem;
            FixedProfile.Value                      =   StStr.strFalse;
            FixedProfile.Order                      =   10;
            FixedProfile.ExtendedGroupName          =   extgrp;
            FixedProfile.EnglishName                =   "Fixed Profile";
            FixedProfile.Description                =   "When checked, module will use the Calling Profile selected in next setting";
            bSettings.AddSetting(FixedProfile);

            try
            {
                SettingItemSpecial MProfile         =   new SettingItemSpecial(PStr.MProfile,new CustomListDataType(Wrapper.Util.ListFromPickList(PStr.callingprofile,PStr.calloutcampaign),StStr.smName,StStr.smVal));
                MProfile.Required                   =   false;
                MProfile.ResourceFile               =   PStr.ResourceFile;
                MProfile.ResourceItem               =   PStr.ResourceItem;
                MProfile.Value                      =   "2";
                MProfile.Order                      =   20;
                MProfile.ExtendedGroupName          =   extgrp;
                MProfile.EnglishName                =   "Calling Profile";
                MProfile.Description                =   "This Calling Profile will be used for this module";
                bSettings.AddSetting(MProfile);
            }
            catch(Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError || LeadProspectorTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]LeadProspectorSI InitSettings calloutcampaign entity not installed in Crm ex: {0}.",ex),(ModuleTraceSwitch.Sw.TraceError) ? ModuleTraceSwitch.Sw.Info:LeadProspectorTrace.Sw.Info);
                SettingItemSpecial MProfile         =   new SettingItemSpecial(PStr.MProfile,new StringDataType());
                MProfile.Required                   =   false;
                MProfile.ResourceFile               =   PStr.ResourceFile;
                MProfile.ResourceItem               =   PStr.ResourceItem;
                MProfile.Value                      =   "Calloutcampaign entity not installed in Crm";
                MProfile.ReadOnly                   =   true;
                MProfile.Order                      =   20;
                MProfile.ExtendedGroupName          =   extgrp;
                MProfile.EnglishName                =   "Calling Profile";
                MProfile.Description                =   "This Calling Profile will be used for this module";
                bSettings.AddSetting(MProfile);
            }

            SettingItemSpecial ShowMeeting          =   new SettingItemSpecial(PStr.ShowMeeting,new BooleanDataType());
            ShowMeeting.Required                    =   false;
            ShowMeeting.ResourceFile                =   PStr.ResourceFile;
            ShowMeeting.ResourceItem                =   PStr.ResourceItem;
            ShowMeeting.Value                       =   StStr.strFalse;
            ShowMeeting.Order                       =   22;
            ShowMeeting.ExtendedGroupName           =   extgrp;
            ShowMeeting.EnglishName                 =   "Show Meeting column";
            ShowMeeting.Description                 =   "When checked, the new meeting column will be displayed";
            bSettings.AddSetting(ShowMeeting);

            SettingItemSpecial ExternalUrl          =   new SettingItemSpecial(PStr.ExternalUrl,new StringDataType());
            ExternalUrl.Required                    =   false;
            ExternalUrl.ResourceFile                =   PStr.ResourceFile;
            ExternalUrl.ResourceItem                =   PStr.ResourceItem;
            ExternalUrl.Order                       =   24;
            ExternalUrl.ExtendedGroupName           =   extgrp;
            ExternalUrl.EnglishName                 =   "External Url";
            ExternalUrl.Description                 =   "Url to use when calling crm server from internet";
            bSettings.AddSetting(ExternalUrl);

            SettingItemSpecial InternalUrl          =   new SettingItemSpecial(PStr.InternalUrl,new StringDataType());
            InternalUrl.Required                    =   false;
            InternalUrl.ResourceFile                =   PStr.ResourceFile;
            InternalUrl.ResourceItem                =   PStr.ResourceItem;
            InternalUrl.Order                       =   26;
            InternalUrl.ExtendedGroupName           =   extgrp;
            InternalUrl.EnglishName                 =   "Internal Url";
            InternalUrl.Description                 =   "Url to use when calling crm server from intranet";
            bSettings.AddSetting(InternalUrl);

            SettingItemSpecial ShowCampaign         =   new SettingItemSpecial(PStr.ShowCampaign,new BooleanDataType());
            ShowCampaign.Required                   =   false;
            ShowCampaign.ResourceFile               =   PStr.ResourceFile;
            ShowCampaign.ResourceItem               =   PStr.ResourceItem;
            ShowCampaign.Value                      =   StStr.strFalse;
            ShowCampaign.Order                      =   30;
            ShowCampaign.ExtendedGroupName          =   extgrp;
            ShowCampaign.EnglishName                =   "Show Campaign";
            ShowCampaign.Description                =   "When checked, display a combobox with campaign";
            bSettings.AddSetting(ShowCampaign);

            SettingItemSpecial FixedCampaign        =   new SettingItemSpecial(PStr.FixedCampaign,new BooleanDataType());
            FixedCampaign.Required                  =   false;
            FixedCampaign.ResourceFile              =   PStr.ResourceFile;
            FixedCampaign.ResourceItem              =   PStr.ResourceItem;
            FixedCampaign.Value                     =   StStr.strFalse;
            FixedCampaign.Order                     =   40;
            FixedCampaign.ExtendedGroupName         =   extgrp;
            FixedCampaign.EnglishName               =   "Fixed Campaign";
            FixedCampaign.Description               =   "When checked, module will use the campain selected in next setting";
            bSettings.AddSetting(FixedCampaign);

            //Fixed campaign
            WSListDataType defCampaign              =   new WSListDataType(CrmStr.campaign,StStr.smName, "ID");
            SettingItemSpecial Campaign             =   new SettingItemSpecial(PStr.MCampaign,defCampaign);
            Campaign.EnglishName                    =   "Campaign";
            Campaign.Order                          =   50;
            Campaign.ResourceFile                   =   PStr.ResourceFile;
            Campaign.ResourceItem                   =   PStr.ResourceItem;
            Campaign.ExtendedGroupName              =   extgrp;
            Campaign.Description                    =   "Select a default campaign to associate with this Rating";
            Campaign.SettingItemsEvent              +=  new SettingItemsEventHandler(Campaign_SettingItemsEvent);
            bSettings.AddSetting(Campaign);

            SettingItemSpecial AutoInterview        =   new SettingItemSpecial(PStr.AutoInterview,new BooleanDataType());
            AutoInterview.Required                  =   false;
			AutoInterview.Order                     =   70;
            AutoInterview.Value                     =   StStr.strTrue;
            AutoInterview.ResourceFile              =   PStr.ResourceFile;
            AutoInterview.ResourceItem              =   PStr.ResourceItem;
			AutoInterview.ExtendedGroupName         =   extgrp;
            AutoInterview.EnglishName               =	"Create Interview";
			AutoInterview.Description               =	"Automatically create an interview on each new phone call";
			bSettings.AddSetting(AutoInterview);           

            AddRadGridPack( bSettings,100, extgrp);
            if ( ModuleTraceSwitch.Sw.TraceVerbose || LeadProspectorTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]LeadProspectorSI InitSettings END.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:LeadProspectorTrace.Sw.Info);
        }
        
        protected void AddRadGridPack(ModuleSettingsDictionary bSettings,int startOrder,string extgrp)
        {
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspectorSI AddRadGridPack BEG startOrder: {0}, bSettings.Count: {1}", startOrder,bSettings.Count), LeadProspectorTrace.Sw.Info);
            startOrder++;
			
            SettingItemSpecial gScrolling	        =	new SettingItemSpecial(PStr.Scroll,new BooleanDataType());
			gScrolling.Order			            =	startOrder++;
            gScrolling.Value			            =	StStr.strTrue;
            gScrolling.ResourceFile                 =   PStr.ResourceFile;
            gScrolling.ResourceItem                 =   PStr.ResourceItem;
			gScrolling.ExtendedGroupName            =   extgrp;
			gScrolling.Description		            =	"True if the grid will be displayed using Scrolling";
            gScrolling.EnglishName		            =	"Scrolling mode for Grid";
			bSettings.AddSetting(gScrolling);

			SettingItemSpecial gPaging		        =	new SettingItemSpecial(PStr.Paging,new BooleanDataType());
			gPaging.Order			                =	startOrder++;
            gPaging.Required                        =   false;
            gPaging.Value			                =	StStr.strTrue;
            gPaging.ResourceFile                    =   PStr.ResourceFile;
            gPaging.ResourceItem                    =   PStr.ResourceItem;
			gPaging.ExtendedGroupName               =   extgrp;
			gPaging.Description		                =	"True if the grid will be displayed using Paging";
            gPaging.EnglishName		                =	"Page mode for Grid";
			bSettings.AddSetting(gPaging);

			SettingItemSpecial pgSz		            =	new SettingItemSpecial(PStr.PageSz,new IntegerDataType()); 
            pgSz.Required                           =   false;
			pgSz.Required			                =	true;
			pgSz.MinValue			                =	10;
			pgSz.MaxValue			                =	500;
			pgSz.Order				                =	startOrder++;
            pgSz.Value				                =	"20";
            pgSz.ResourceFile                       =   PStr.ResourceFile;
            pgSz.ResourceItem                       =   PStr.ResourceItem;
			pgSz.ExtendedGroupName                  =   extgrp;
			pgSz.Description		                =	"Number of records displayed in each page";
            pgSz.EnglishName		                =   "Grid Page Size";
			bSettings.AddSetting(pgSz);

            SettingItemSpecial IgnoreFormating      =   new SettingItemSpecial(PStr.IgnoreFormating,new BooleanDataType());
            IgnoreFormating.Required                =   false;
			IgnoreFormating.Order                   =   startOrder++;
            IgnoreFormating.Value                   =   StStr.strTrue;
            IgnoreFormating.ResourceFile            =   PStr.ResourceFile;
            IgnoreFormating.ResourceItem            =   PStr.ResourceItem;
			IgnoreFormating.ExtendedGroupName       =   extgrp;
            IgnoreFormating.EnglishName             =	"Ignore formating";
			IgnoreFormating.Description             =	"Ignore formating on export";
			bSettings.AddSetting(IgnoreFormating);           
            
            SettingItemSpecial IgnorePaging         =   new SettingItemSpecial(PStr.IgnorePaging,new BooleanDataType());
            IgnorePaging.Required                   =   false;
			IgnorePaging.Order                      =   startOrder++;
            IgnorePaging.Value                      =   StStr.strTrue;
            IgnorePaging.ResourceFile               =   PStr.ResourceFile;
            IgnorePaging.ResourceItem               =   PStr.ResourceItem;
			IgnorePaging.ExtendedGroupName          =   extgrp;
            IgnorePaging.EnglishName                =	"Ignore paging";
			IgnorePaging.Description                =	"Ignore paging on export";
			bSettings.AddSetting(IgnorePaging);           
            
            SettingItemSpecial OpenInNewWindow      =   new SettingItemSpecial(PStr.OpenInNewWindow,new BooleanDataType());
            OpenInNewWindow.Required                =   false;
			OpenInNewWindow.Order                   =   startOrder++;
            OpenInNewWindow.Value                   =   StStr.strTrue;
            OpenInNewWindow.ResourceFile            =   PStr.ResourceFile;
            OpenInNewWindow.ResourceItem            =   PStr.ResourceItem;
			OpenInNewWindow.ExtendedGroupName       =   extgrp;
            OpenInNewWindow.EnglishName             =	"Open in new window";
			OpenInNewWindow.Description             =	"Open in new window on export";
			bSettings.AddSetting(OpenInNewWindow);           

            SettingItemSpecial AllowFilteringByColumn   =   new SettingItemSpecial(PStr.AllowFilteringByColumn,new BooleanDataType());
            AllowFilteringByColumn.Required             =   false;
			AllowFilteringByColumn.Order                =   startOrder++;
            AllowFilteringByColumn.Value                =   StStr.strFalse;
            AllowFilteringByColumn.ResourceFile         =   PStr.ResourceFile;
            AllowFilteringByColumn.ResourceItem         =   PStr.ResourceItem;
			AllowFilteringByColumn.ExtendedGroupName    =   extgrp;
            AllowFilteringByColumn.EnglishName          =	"Allow filtering by column";
			AllowFilteringByColumn.Description          =	"Allow client side filtering of values by column";
			bSettings.AddSetting(AllowFilteringByColumn);           

            SettingItemSpecial GroupingEnabled      =   new SettingItemSpecial(PStr.GroupingEnabled,new BooleanDataType());
            GroupingEnabled.Required                =   false;
			GroupingEnabled.Order                   =   startOrder++;
            GroupingEnabled.Value                   =   StStr.strFalse;
            GroupingEnabled.ResourceFile            =   PStr.ResourceFile;
            GroupingEnabled.ResourceItem            =   PStr.ResourceItem;
			GroupingEnabled.ExtendedGroupName       =   extgrp;
            GroupingEnabled.EnglishName             =	"Grouping enabled";
			GroupingEnabled.Description             =	"Allow client side grouping by columns";
			bSettings.AddSetting(GroupingEnabled);           
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspectorSI AddRadGridPack END bSettings.Count: {0}", bSettings.Count), LeadProspectorTrace.Sw.Info);
        }
        
        /// <summary>
        /// Used to set the good display value in Campaign when loaded from DB
        /// </summary>
        void Campaign_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( LeadProspectorTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullInterviewSI Campaign_SettingItemsEvent Guid: {0}", e.Data),LeadProspectorTrace.Sw.Info);
            Guid custId                     =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynCampaign dynac            =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,new ResetWrapperHandler(ResetWrapper),custId);
            WSListDataType defCampaign      =   (WSListDataType )((SettingItem)sender).DataType;
            defCampaign.DisplayTextValue    =   dynac.name;
            if ( LeadProspectorTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullInterviewSI ModuleOwner_SettingItemsEvent END name: {0}", dynac.name),LeadProspectorTrace.Sw.Info);
        }
    }

    public partial class LeadProspector : PortalCRMModuleControl
    {

		#region Global Implementation

        public override Guid GuidID 
		{
			get
			{
				return new Guid("{CB27AA5B-4FBD-40bb-A6A9-72E1EA2FE07F}");
			}
		}

		#endregion Global Implementation

        

        bool ShowMeeting
        {
            get { return Settings[PStr.ShowMeeting].ToBool(); }
        }

        bool ShowCampaign
        {
            get { return Settings[PStr.ShowCampaign].ToBool(); }
        }

        bool FixedCampaign
        {
            get { return Settings[PStr.FixedCampaign].ToBool(); }
        }
        
        bool FixedProfile
        {
            get { return Settings[PStr.FixedProfile].ToBool(); }
        }
 
        #region Ctor

        /// <summary>
		/// Ctor Set the properties of the module
		/// </summary>
        public LeadProspector()
        {
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector Ctor enter at: {0}", DateTime.UtcNow), LeadProspectorTrace.Sw.Info);
        }

       public override string ExtendedResourcesGroup 
		{
            get
            {
       			const string extgrp                     =   "LEADPROSPECTOR";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new LeadProspectorSI(bSettings,this);
        }

        #endregion Ctor

        protected void Page_Load(object sender, EventArgs e)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose || LeadProspectorTrace.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector Page_Load BEG IsPostBack: {0}",IsPostBack),(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:LeadProspectorTrace.Sw.Info);
           if ( ! IsPostBack )
            {
                // Fill picklist combos
                CbCallingProfile.DataTextField              =   StStr.smName;
                CbCallingProfile.DataValueField             =   StStr.smVal;
                CbCallingProfile.DataSource                 =   Wrapper.Util.ListFromPickList(PStr.callingprofile,PStr.calloutcampaign);
                CbCallingProfile.DataBind();
                int selProfile                              =   Settings[PStr.MProfile].ToInt();
                if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector Page_Load selProfile: {0}", selProfile), LeadProspectorTrace.Sw.Info);
                RadComboBoxItem it                          =   CbCallingProfile.Items.FindItemByValue(selProfile.ToString());
                if ( it != null )
                    it.Selected                             =   true;
                if ( FixedProfile )
                    CbCallingProfile.Enabled                =   false;

                CbStatusCallout.DataTextField               =   StStr.smName;
                CbStatusCallout.DataValueField              =   StStr.smVal;
                SortedList<int,string> Lst                  =   Wrapper.Util.GetAllStatusCodes(PStr.calloutcampaign);
                ArrayList Al                                 =   new ArrayList();
                foreach(int key in Lst.Keys)
                    Al.Add(new CrmListInt(Lst[key],key));
                if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector Page_Load CbStatusCallout Count: {0}", Al.Count), LeadProspectorTrace.Sw.Info);
                CbStatusCallout.DataSource                  =   Al;
                CbStatusCallout.DataBind();
                if ( CbStatusCallout.Items.Count > 0 )
                   CbStatusCallout.Items[0].Selected        =   true;

                CbStatusInterView.DataTextField             =   StStr.smName;
                CbStatusInterView.DataValueField            =   StStr.smVal;
                Lst                                         =   Wrapper.Util.GetAllStatusCodes(PStr.interview);
                Al                                          =   new ArrayList();
                foreach(int key in Lst.Keys)
                    Al.Add(new CrmListInt(Lst[key],key));
                if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector Page_Load CbStatusInterView Count: {0}", Al.Count), LeadProspectorTrace.Sw.Info);
                CbStatusInterView.DataSource                =   Al;
                CbStatusInterView.DataBind();
                if ( CbStatusInterView.Items.Count > 0 )
                   CbStatusInterView.Items[0].Selected      =   true;

                //Campaign 
                Guid CampaignId                             =   Guid.Empty;
                if ( FixedCampaign )
                    CampaignId                              =   Settings[PStr.MCampaign].ToGuid();
                 if ( CampaignId != Guid.Empty )
                {
                    ADNDynCampaign dnc                      =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,ResetWrapper,CampaignId);
                    if ( dnc != null )
                    {
                        RadComboBoxItem itc                 =    new RadComboBoxItem(dnc.name,CampaignId.ToString());
                        itc.Selected                        =   true;
                        CbCampaign.Items.Add(itc);
                        CbCampaign.DataBind();
                        if (LeadProspectorTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector Page_Load Campaign: {0}.",dnc.name),LeadProspectorTrace.Sw.Info);
                    }
                }
                // Show campaign combo ?
                if ( !ShowCampaign )
                    dcampaign.Visible                       =   false;

				//force paging according settings
				RadGrid1.AllowPaging	                    =	Settings[PStr.Paging].ToBool();
                RadGrid1.AllowFilteringByColumn             =	Settings[PStr.AllowFilteringByColumn].ToBool();
                RadGrid1.GroupingEnabled                    =	Settings[PStr.GroupingEnabled].ToBool();
				if ( RadGrid1.AllowPaging )
						RadGrid1.PageSize                   =   Settings[PStr.PageSz].ToInt();

            }
            if ( ModuleTraceSwitch.Sw.TraceVerbose || LeadProspectorTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]LeadProspector Page_Load END.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:LeadProspectorTrace.Sw.Info);
        }
        /*
        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemDataBound BEG e.Item.OwnerTableView.Name: {0}, e.Item: {1}",
                    e.Item.OwnerTableView.Name,e.Item),LeadProspectorTrace.Sw.Info);
            if ( e.Item.OwnerTableView.Name == "Interviews" )
            {
                if (e.Item is GridEditFormItem )
                {
                    if (LeadProspectorTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemDataBound Item: {0}, Type: {1}, IsInEditMode: {2}",
                            e.Item,e.Item.ItemType,e.Item.IsInEditMode),LeadProspectorTrace.Sw.Info);
                    GridEditFormItem item           =   (GridEditFormItem)e.Item;
                }
                else if (e.Item is GridDataItem)
                {
                    GridDataItem item               =   e.Item as GridDataItem;
                }
            }
            else if ( e.Item.OwnerTableView.Name == "Contacts" )
            {
                if (e.Item is GridEditFormItem )
                {
                    if (LeadProspectorTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemDataBound Item: {0}, Type: {1}, IsInEditMode: {2}",
                            e.Item,e.Item.ItemType,e.Item.IsInEditMode),LeadProspectorTrace.Sw.Info);
                    GridEditFormItem item       =   (GridEditFormItem)e.Item;
                }
                else if (e.Item is GridDataItem)
                {
                    GridDataItem item   =   e.Item as GridDataItem;
                }
            }
            else if ( e.Item.OwnerTableView.Name == "CalloutCampaigns" )
            {
                if (e.Item is GridEditFormItem )
                {
                    if (LeadProspectorTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemDataBound Item: {0}, Type: {1}, IsInEditMode: {2}",
                            e.Item,e.Item.ItemType,e.Item.IsInEditMode),LeadProspectorTrace.Sw.Info);
                    GridEditFormItem item       =   (GridEditFormItem)e.Item;
                }
                else if (e.Item is GridDataItem)
                {
                    GridDataItem item   =   e.Item as GridDataItem;
                }
            }
        }
        */

        string CrmServerUrl
        {
            get
            {
                string ExternalUrl                  =   Settings[PStr.ExternalUrl].Value;
                string InternalUrl                  =   Settings[PStr.InternalUrl].Value;
                bool localReq                       =   ( ( Request.LogonUserIdentity != null ) && Request.LogonUserIdentity.IsAuthenticated );
                string url                          =   Wrapper.CrmServiceUrl.ToLowerInvariant();
                int idx                             =   url.IndexOf("mscrmservice");
 			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector CrmServerUrl url: {0}, isAdminPortal: {1}, localReq: {2}, ExternalUrl: {3}, InternalUrl: {4}",
                       new object[]{Request.Url,Config.IsAdminPortal,localReq,ExternalUrl,InternalUrl}),LeadProspectorTrace.Sw.Info);
                    // When under https scheme we are called from internet, else from intranet
                if ( Request.Url.Scheme == "https" )
                {
                    if ( !string.IsNullOrEmpty(ExternalUrl) )
                        return ExternalUrl;
                    return string.Format("https://{0}.nicecrm.com/",Wrapper.OrganizationName);
                }
                 if ( !string.IsNullOrEmpty(InternalUrl) )
                    return InternalUrl;
                return string.Format("{0}{1}/",url.Substring(0,idx),Wrapper.OrganizationName);
            }
        }


        void RawPopup(string url)
        {
            // build the popup command
            string popUpOptions = "toolbar=0,location=0,directories=0,status=0,menubar=1,scrollbars=1,resizable=1,width=1024,height=768,screenX=15,screenY=15,top=15,left=15";
            string script       =   string.Format("raw_popup('{0}','_blank','{1}');",url,popUpOptions);
            ADNPage.AjaxManager.ResponseScripts.Add(script);
        }

        void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
			if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand CommandName: {0}, SelectedIndexes.Count: {1}",
                    e.CommandName,RadGrid1.SelectedIndexes.Count),LeadProspectorTrace.Sw.Info);
            /* We create a new phone call with:
             * - the Calloutcampaign in regarding
             * - the contact as 'to'
             Optionnally we attach a new Interview with same type as the calloutcampaign
             * We Open the phone call in a new window
             */

            if ( e.CommandName == "NewPhone" )
            {
                GridDataItem dataItem               =  e.Item as GridDataItem;
                Guid contactid                      =   (Guid)dataItem.GetDataKeyValue("contactid");
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand contactid: {0}",contactid),LeadProspectorTrace.Sw.Info);
			    ADNDynContact dynC                  =   DynEntity.GetFromCache<ADNDynContact>(CrmStr.contact,Wrapper,ResetWrapper,contactid);  
                dataItem                            =   e.Item.OwnerTableView.ParentItem as GridDataItem;
                Guid CalloutCampaignid              =   (Guid)dataItem.GetDataKeyValue("adn_calloutcampaignid");
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand CalloutCampaignid: {0}",CalloutCampaignid),LeadProspectorTrace.Sw.Info);
                ADNDynCalloutCampaign dynCC         =   DynEntity.GetFromCache<ADNDynCalloutCampaign>(PStr.calloutcampaign,Wrapper,ResetWrapper,CalloutCampaignid);  
                ADNDynPhoneInterview dynPi          =   new ADNDynPhoneInterview(Wrapper,string.Format("Interview {0} for {1}",dynC.fullname,dynCC.subject));
                dynPi.directioncode                 =   true;
                ADNDynSystemUser DynSender          =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,ResetWrapper,Wrapper.userId);
                dynPi.AddSender(DynSender);
                dynPi.AddDest(dynC);
                dynPi.DefaultRegardingObjectName    =   PStr.calloutcampaign;
                dynPi.regardingobjectid             =   CalloutCampaignid;
                dynPi.Create();
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand Created Phone call activityid: {0}",dynPi.activityid),LeadProspectorTrace.Sw.Info);
                if ( Settings[PStr.AutoInterview].ToBool() )
                {
                    ADNDynInterview dynI            =   new ADNDynInterview(Wrapper,dynPi.subject);
                    dynI.contactid                  =   contactid;
                    dynI.callingprofile             =   dynCC.callingprofile;
                    dynI.callingcampaignid          =   dynCC.calloutcampaignid;
                    if ( dynCC.campaignid != Guid.Empty )
                        dynI.campaignid             =   dynCC.campaignid;
                    dynI.Create();
			        if (LeadProspectorTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand Created Interview interviewid: {0}",dynI.interviewid),LeadProspectorTrace.Sw.Info);
                    dynPi.type                      =   dynCC.callingprofile;
                    dynPi.interviewid               =   dynI.interviewid;
                    dynPi.Update();
			        if (LeadProspectorTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand Updated Phonecall callingprofile: {0}",dynCC.callingprofile),LeadProspectorTrace.Sw.Info);
                }
                // Open Phone call
                string url                          =   string.Format("{0}activities/phone/edit.aspx?id={1}",CrmServerUrl,dynPi.activityid);
                //string url                          =   string.Format("/activities/phone/edit.aspx?id={0}",dynPi.activityid);
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand redirecting url: {0}",url),LeadProspectorTrace.Sw.Info);
                RawPopup(url);
            }
            else if ( e.CommandName == "NewMeeting" )
            {
                GridDataItem dataItem               =  e.Item as GridDataItem;
                Guid contactid                      =   (Guid)dataItem.GetDataKeyValue("contactid");
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand contactid: {0}",contactid),LeadProspectorTrace.Sw.Info);
			    ADNDynContact dynC                  =   DynEntity.GetFromCache<ADNDynContact>(CrmStr.contact,Wrapper,ResetWrapper,contactid);  
                dataItem                            =   e.Item.OwnerTableView.ParentItem as GridDataItem;
                Guid CalloutCampaignid              =   (Guid)dataItem.GetDataKeyValue("adn_calloutcampaignid");
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand CalloutCampaignid: {0}",CalloutCampaignid),LeadProspectorTrace.Sw.Info);
                ADNDynCalloutCampaign dynCC         =   DynEntity.GetFromCache<ADNDynCalloutCampaign>(PStr.calloutcampaign,Wrapper,ResetWrapper,CalloutCampaignid);  
                ADNDynAppointmentInterview dynPi    =   new ADNDynAppointmentInterview(Wrapper,string.Format("Interview {0} for {1}",dynC.fullname,dynCC.subject));
                ADNDynSystemUser DynSender          =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,ResetWrapper,Wrapper.userId);
                dynPi.AddOrganizer(DynSender);
                dynPi.AddRequiredAttende(dynC);
                dynPi.DefaultRegardingObjectName    =   PStr.calloutcampaign;
                dynPi.regardingobjectid             =   CalloutCampaignid;
                dynPi.Create();
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand Created Appointment activityid: {0}",dynPi.activityid),LeadProspectorTrace.Sw.Info);
                if ( Settings[PStr.AutoInterview].ToBool() )
                {
                    ADNDynInterview dynI            =   new ADNDynInterview(Wrapper,dynPi.subject);
                    dynI.contactid                  =   contactid;
                    dynI.callingprofile             =   dynCC.callingprofile;
                    dynI.callingcampaignid          =   dynCC.calloutcampaignid;
                    if ( dynCC.campaignid != Guid.Empty )
                        dynI.campaignid             =   dynCC.campaignid;
                    dynI.Create();
			        if (LeadProspectorTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand Created Interview interviewid: {0}",dynI.interviewid),LeadProspectorTrace.Sw.Info);
                    dynPi.type                      =   dynCC.callingprofile;
                    dynPi.interviewid               =   dynI.interviewid;
                    dynPi.Update();
			        if (LeadProspectorTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand Updated Appointment callingprofile: {0}",dynCC.callingprofile),LeadProspectorTrace.Sw.Info);
                }
                string url                          =   string.Format("{0}activities/appointment/edit.aspx?id={1}",CrmServerUrl,dynPi.activityid);
                //string url                          =   string.Format("/activities/appointment/edit.aspx?id={0}",dynPi.activityid);
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand redirecting url: {0}",url),LeadProspectorTrace.Sw.Info);
                RawPopup(url);
            }
            else if ( e.CommandName == "OpenCrmContact" )
            {
                GridDataItem dataItem               =  e.Item as GridDataItem;
                Guid contactid                      =   (Guid)dataItem.GetDataKeyValue("contactid");
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand contactid: {0}",contactid),LeadProspectorTrace.Sw.Info);

                string url                          =   string.Format("{0}SFA/conts/edit.aspx?id={1}",CrmServerUrl,contactid);
                //string url                          =   string.Format("/SFA/conts/edit.aspx?id={0}",contactid);
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand redirecting url: {0}",url),LeadProspectorTrace.Sw.Info);
                RawPopup(url);
            }
            else if ( e.CommandName == "OpenCrmInterview" )
            {
                GridDataItem dataItem               =  e.Item as GridDataItem;
                Guid interviewid                      =   (Guid)dataItem.GetDataKeyValue(PStr.interviewid);
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand interviewid: {0}",interviewid),LeadProspectorTrace.Sw.Info);

                string url                          =   string.Format("{0}UserDefined/edit.aspx?etn=adn_interview&id={1}",CrmServerUrl,interviewid);
                //string url                          =   string.Format("/UserDefined/edit.aspx?etn=adn_interview&id={0}",interviewid);
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand redirecting url: {0}",url),LeadProspectorTrace.Sw.Info);
                RawPopup(url);
            }
            else if ( e.CommandName == "OpenCrmCalloutCampaign" )
            {
                GridDataItem dataItem               =  e.Item as GridDataItem;
                Guid calloutcampaignid                      =   (Guid)dataItem.GetDataKeyValue(PStr.calloutcampaignid);
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand calloutcampaignid: {0}",calloutcampaignid),LeadProspectorTrace.Sw.Info);

                string url                          =   string.Format("{0}UserDefined/edit.aspx?etn=adn_calloutcampaign&id={1}",CrmServerUrl,calloutcampaignid);
                //string url                          =   string.Format("/UserDefined/edit.aspx?etn=adn_calloutcampaign&id={0}",calloutcampaignid);
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_ItemCommand redirecting url: {0}",url),LeadProspectorTrace.Sw.Info);
                RawPopup(url);
            }
        }

        DataTable GetAllCallout()
        {
            DataTable Tb    =   null;
			if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]LeadProspector GetAllCallout BEG.",ModuleTraceSwitch.Sw.Info);
            try
            {
                Guid CampaignId                         =   Guid.Empty;
                if ( ShowCampaign )
                {
                    if ( FixedCampaign )
                        CampaignId                          =   Settings[PStr.MCampaign].ToGuid();
                    else if ( !string.IsNullOrEmpty(CbCampaign.SelectedValue) ) 
                    {
			            if (LeadProspectorTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllCallout CbCampaign.SelectedValue: {0}",CbCampaign.SelectedValue),LeadProspectorTrace.Sw.Info);
                        try
                        {
                            CampaignId = new Guid(CbCampaign.SelectedValue);
                        }
                        catch(Exception ex)
                        {
                            if ( LeadProspectorTrace.Sw.TraceError )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]LeadProspector GetAllCallout new Guid ex: {0}", ex),LeadProspectorTrace.Sw.Info);
                     
                        }
                    }
                }
			    if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllCallout CampaignId: {0}",CampaignId),LeadProspectorTrace.Sw.Info);

                InternalQueryExpression qe          =   new InternalQueryExpression();
                qe.ColumnSet                        =   new InternalAllColumns();
                qe.EntityName                       =   PStr.calloutcampaign;
                qe.Criteria                         =   new InternalFilterExpression();
                qe.Criteria.FilterOperator          =   InternalLogicalOperator.And;
                List<InternalConditionExpression> lst   =   new List<InternalConditionExpression>();
                //lst.Add(CRMUtil.StateCodeIsActiveCondition);
                
                InternalConditionExpression ce      =   null;
                if ( CampaignId != Guid.Empty )
                {
                    ce                              =   new InternalConditionExpression();
                    ce.Operator                     =   InternalConditionOperator.Equal;
                    ce.AttributeName                =   PStr.campaignid;
                    ce.Values                       =   new string[]{CampaignId.ToString()};
                    lst.Add(ce);
                }
                
                int callProfile                     =   int.Parse(CbCallingProfile.SelectedValue);
                if ( FixedProfile )
                    callProfile                     =   Settings[PStr.MProfile].ToInt();
		        if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllCallout callProfile: {0}",callProfile),LeadProspectorTrace.Sw.Info);
                ce                                  =   new InternalConditionExpression();
                ce.Operator                         =   InternalConditionOperator.Equal;
                ce.AttributeName                    =   PStr.callingprofile;
                ce.Values                           =   new object[]{callProfile};
                lst.Add(ce);
                if ( CbStatusCallout.SelectedIndex != -1 )
                {
		            if (LeadProspectorTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllCallout CbStatusCallout.SelectedValue: {0}",CbStatusCallout.SelectedValue),LeadProspectorTrace.Sw.Info);
                    int CallStatus                      =   int.Parse(CbStatusCallout.SelectedValue);
		            if (LeadProspectorTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllCallout CallStatus: {0}",CallStatus),LeadProspectorTrace.Sw.Info);
                    ce                                  =   new InternalConditionExpression();
                    ce.Operator                         =   InternalConditionOperator.Equal;
                    ce.AttributeName                    =   CrmStr.statuscode;
                    ce.Values                           =   new object[]{CallStatus};
                    lst.Add(ce);
                }                
                qe.Criteria.Conditions              =   new InternalConditionExpression[lst.Count];
                for (int i=0; i < lst.Count; i++ )
                    qe.Criteria.Conditions[i]       =   lst[i];
		        
                if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllCallout lst.Count: {0}",lst.Count),LeadProspectorTrace.Sw.Info);
                
                GenericDynQueryMultiple<ADNDynCalloutCampaign> allEntQuery  =   new GenericDynQueryMultiple<ADNDynCalloutCampaign>(Wrapper,ResetWrapper,PStr.calloutcampaign);
                Tb                                  =   allEntQuery.retrieveDatatable(qe);
		        if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllCallout Count: {0}",Tb.Rows.Count),LeadProspectorTrace.Sw.Info);
            }
            catch(Exception ex)
            {
                if ( LeadProspectorTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]LeadProspector GetAllCallout ex: {0}", ex),LeadProspectorTrace.Sw.Info);
                throw;
            }
            return Tb;
        }

        protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
			if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_NeedDataSource BEG e.IsFromDetailTable: {0}",
                    e.IsFromDetailTable),LeadProspectorTrace.Sw.Info);
            if (!e.IsFromDetailTable)
            {
                RadGrid1.DataSource         =   GetAllCallout();
            }
        }

        DataTable GetAllContacts(Guid accountid)
        {
		    if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllContacts BEG accountid: {0}",accountid),LeadProspectorTrace.Sw.Info);
            DataTable Tb                        =   null;    
            try
            {
		        if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllContacts accountid: {0}",accountid),LeadProspectorTrace.Sw.Info);
                InternalQueryExpression qe      =   new InternalQueryExpression();
                qe.ColumnSet                    =   new InternalAllColumns();
                qe.EntityName                   =   CrmStr.contact;
                qe.Criteria                     =   new InternalFilterExpression();
                InternalConditionExpression ce  =   new InternalConditionExpression();
                ce.Operator                     =   InternalConditionOperator.Equal;
                ce.AttributeName                =   CrmStr.parentcustomerid;
                ce.Values                       =   new string[]{accountid.ToString()};
                qe.Criteria.FilterOperator      =   InternalLogicalOperator.And;
                qe.Criteria.Conditions          =   new InternalConditionExpression[]{CRMUtil.StateCodeIsActiveCondition,ce};
                
                GenericDynQueryMultiple<ADNDynContact> allEntQuery  =   new GenericDynQueryMultiple<ADNDynContact>(Wrapper,ResetWrapper,CrmStr.contact);
                Tb                              =   allEntQuery.retrieveDatatable(qe);
		        if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllContacts Count: {0}",Tb.Rows.Count),LeadProspectorTrace.Sw.Info);
            }
            catch(Exception ex)
            {
                if ( LeadProspectorTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]LeadProspector GetAllContacts ex: {0}", ex),LeadProspectorTrace.Sw.Info);
                throw;
            }
            return Tb;
        }

        DataTable GetAllInterViews(Guid contactid)
        {
		    if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllInterViews BEG contactid: {0}",contactid),LeadProspectorTrace.Sw.Info);
            DataTable Tb                        =   null;    
            try
            {
		        if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllInterViews contactid: {0}",contactid),LeadProspectorTrace.Sw.Info);
                InternalQueryExpression qe      =   new InternalQueryExpression();
                qe.ColumnSet                    =   new InternalAllColumns();
                qe.EntityName                   =   PStr.interview;
                qe.Criteria                     =   new InternalFilterExpression();
                InternalConditionExpression ce  =   new InternalConditionExpression();
                ce.Operator                     =   InternalConditionOperator.Equal;
                ce.AttributeName                =   PStr.contactid;
                ce.Values                       =   new string[]{contactid.ToString()};
                qe.Criteria.FilterOperator      =   InternalLogicalOperator.And;
                if ( CbStatusInterView.SelectedIndex != -1 )
                {
                    int IStatus                     =   int.Parse(CbStatusInterView.SelectedValue);
	                if (LeadProspectorTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllInterViews IStatus: {0}",IStatus),LeadProspectorTrace.Sw.Info);
                    InternalConditionExpression ce2 =   new InternalConditionExpression();
                    ce2.Operator                    =   InternalConditionOperator.Equal;
                    ce2.AttributeName               =   CrmStr.statuscode;
                    ce2.Values                      =   new object[]{IStatus};
                    qe.Criteria.Conditions          =   new InternalConditionExpression[]{CRMUtil.StateCodeIsActiveCondition,ce,ce2};
                }                    
                else qe.Criteria.Conditions          =   new InternalConditionExpression[]{CRMUtil.StateCodeIsActiveCondition,ce};
                GenericDynQueryMultiple<ADNDynInterview> allEntQuery  =   new GenericDynQueryMultiple<ADNDynInterview>(Wrapper,ResetWrapper,PStr.interview);
                Tb                              =   allEntQuery.retrieveDatatable(qe);
		        if (LeadProspectorTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector GetAllInterViews Count: {0}",Tb.Rows.Count),LeadProspectorTrace.Sw.Info);
            }
            catch(Exception ex)
            {
                if ( LeadProspectorTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]LeadProspector GetAllInterViews ex: {0}", ex),LeadProspectorTrace.Sw.Info);
                throw;
            }
            return Tb;
        }

        protected void RadGrid1_DetailTableDataBind(object source, Telerik.Web.UI.GridDetailTableDataBindEventArgs e)
        {
			if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_DetailTableDataBind BEG e.DetailTableView.Name: {0}",
                    e.DetailTableView.Name),LeadProspectorTrace.Sw.Info);
            GridDataItem dataItem                       =   (GridDataItem)e.DetailTableView.ParentItem;
            switch (e.DetailTableView.Name)
            {
                case "Contacts":
                    {
                        Guid adn_accountid             =   (Guid)dataItem.GetDataKeyValue("adn_accountid");
			            if (LeadProspectorTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_DetailTableDataBind adn_accountid: {0}",
                                adn_accountid),LeadProspectorTrace.Sw.Info);
                        DataTable Tb                    =   GetAllContacts(adn_accountid);
                        if ( LeadProspectorTrace.Sw.TraceVerbose )
                        {
                            Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_DetailTableDataBind Contacts Count: {0}",Tb.Rows.Count),LeadProspectorTrace.Sw.Info);
                            foreach ( DataRow rw in Tb.Rows )
                            {
                                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_DetailTableDataBind Contacts contactid: {0}, parentcustomerid: {1}",
                                    rw[CrmStr.contactid],rw[CrmStr.parentcustomerid]),LeadProspectorTrace.Sw.Info);
                            }
                        }
                        e.DetailTableView.DataSource    =   Tb;
                        break;
                    }

                case "Interviews":
                    {
                        Guid contactid               =   (Guid)dataItem.GetDataKeyValue("contactid");
			            if (LeadProspectorTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadProspector RadGrid1_DetailTableDataBind contactid: {0}",
                                contactid),LeadProspectorTrace.Sw.Info);
                        e.DetailTableView.DataSource    =   GetAllInterViews(contactid);
                        break;
                    }
            }
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]LeadProspector RadGrid1_DetailTableDataBind END.",LeadProspectorTrace.Sw.Info);
        }

        void CbStatusInterView_SelectedIndexChanged(object o,RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]LeadProspector CbStatusInterView_SelectedIndexChanged BEG.",LeadProspectorTrace.Sw.Info);
            RadGrid1.Rebind();
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]LeadProspector CbStatusInterView_SelectedIndexChanged END.",LeadProspectorTrace.Sw.Info);
        }

        void CbStatusCallout_SelectedIndexChanged(object o,RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]LeadProspector CbStatusCallout_SelectedIndexChanged BEG.",LeadProspectorTrace.Sw.Info);
            RadGrid1.Rebind();
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]LeadProspector CbStatusCallout_SelectedIndexChanged END.",LeadProspectorTrace.Sw.Info);
        }

        void CbCallingProfile_SelectedIndexChanged(object o,RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]LeadProspector CbCallingProfile_SelectedIndexChanged BEG.",LeadProspectorTrace.Sw.Info);
            RadGrid1.Rebind();
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]LeadProspector CbCallingProfile_SelectedIndexChanged END.",LeadProspectorTrace.Sw.Info);
        }

        void  CbCampaign_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]LeadProspector CbCampaign_SelectedIndexChanged BEG.",LeadProspectorTrace.Sw.Info);
            RadGrid1.Rebind();
            if (LeadProspectorTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]LeadProspector CbCampaign_SelectedIndexChanged END.",LeadProspectorTrace.Sw.Info);
        }

        #region Std overrides 

        /// <summary>
        /// To be able to popupraw
        /// </summary>
        protected override void OnPreRender(EventArgs e)
        {
            string gPath        =   AddonNice.Settings.Path.ToAbsolute(Config.PortalScriptsPath + "/popup.js");
            ADNPage.RegisterADNClientScriptInclude("adn_popup",gPath);
            base.OnPreRender(e);
        }

        /// <summary>
        /// Triggered from Page.OnPreInit
        /// We must set the Add button before buttons are initialized by base method
        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            string strcult              =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
        }

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent()
		{
            Load                                    +=  new EventHandler(Page_Load);
            RadGrid1.NeedDataSource                 +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.DetailTableDataBind            +=  new GridDetailTableDataBindEventHandler(RadGrid1_DetailTableDataBind);
            RadGrid1.ItemCommand                    +=  new GridCommandEventHandler(RadGrid1_ItemCommand);
            //RadGrid1.ItemDataBound          +=  new GridItemEventHandler(RadGrid1_ItemDataBound);
            if ( !FixedProfile )
            {
                CbCallingProfile.AutoPostBack       = true;
                CbCallingProfile.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(CbCallingProfile_SelectedIndexChanged);
            }
            CbStatusCallout.AutoPostBack            =   true;
            CbStatusCallout.SelectedIndexChanged    +=  new RadComboBoxSelectedIndexChangedEventHandler(CbStatusCallout_SelectedIndexChanged);
            
            CbStatusInterView.AutoPostBack          =   true;
            CbStatusInterView.SelectedIndexChanged  +=  new RadComboBoxSelectedIndexChangedEventHandler(CbStatusInterView_SelectedIndexChanged);
            if ( ShowCampaign && !FixedCampaign )
            {
                CbCampaign.AutoPostBack             =   true;
                CbCampaign.SelectedIndexChanged     +=  new RadComboBoxSelectedIndexChangedEventHandler(CbCampaign_SelectedIndexChanged);
            }
            if ( ShowMeeting )
            {
                GridColumn gcol                     =   RadGrid1.MasterTableView.DetailTables[0].Columns.FindByUniqueNameSafe("NewMeeting");
                if ( gcol != null )
                {
                    gcol.Visible                    =   true;
                    if (LeadProspectorTrace.Sw.TraceVerbose)
                        Trace2.WriteLine("[V]LeadProspector CbCampaign_SelectedIndexChanged END.",LeadProspectorTrace.Sw.Info);
                }
            }
 		}

        #endregion
    }

}